<?php

namespace App\Http\Controllers;

use App\Models\Goods;
use App\Models\Order;
use App\Models\Team;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class GoodsController extends Controller
{
    public function index(Request $request)
    {
//        $pageNum = request()->input('current_page', 1);
//        $pageSize = request()->input('page_size', 10);
        $perPage = $request->get('perPage', 10);

        $user = $request->user();

        $result = Goods::where('auto_time','<', date('Y-m-d h:i:s'))->orWhere('g_num',0)->update(['is_display' => 0]);
        $data = Goods::with('team_info', 'org_info');

        if($request->get('type') === '0' || $request->get('type'))
        {
            $data = $data->where('type', $request->get('type'));
        }
        if($request->get('is_display') === '0' || $request->get('is_display'))
        {
            $data = $data->where('is_display', $request->get('is_display'));
        }
        if($request->get('team_id'))
        {
            $data = $data->where('team_id', $request->get('team_id'));
        }
        if($request->get('keyword'))
        {
            $data = $data->where('g_name','like',"%{$request->get('keyword')}%");
        }

        $org_id = $request->get('org_id', 0);

        if($user->type == 3){
            $org_id = $user->org_id;
        } else if($user->type == 2){
            $data = $data->where('team_id',$user->team_id);
        }
        if ($org_id) {
            $data = $data->where('org_id','=', $org_id);
        }

//        $data = $data->orderBy('is_recommend', 'desc')->orderBy('id', 'desc');
        $data = $data->orderBy('is_recommend', 'desc')->orderBy('end_time', 'asc');

        $data = $data->paginate($perPage)->toArray();
        $info = $data['data'];

        for ($i = 0; $i < count($info); $i++){
            $info[$i]['orders_num'] = Order::where('goods_id',$info[$i]['id'])->count();
            $info[$i]['success_orders'] = Order::where('goods_id',$info[$i]['id'])->where('state',1)->count();
        }
        $data['data'] = $info;
//        $count = $data->count();

//        $pageInfo = [
//            "current_page" => intval($pageNum),
//            "total_page" => ceil($count / $pageSize),
//            "page_size" => intval($pageSize)
//        ];

        return $this->returnJSON([
            'count' => $data['total'],
            'rows' => $data['data']
        ]);
    }

    public function show(Request $request,$id)
    {
        $user = $request->user();
        $data =  Goods::with('org_info', 'team_info');

        if($user->type == 4){
            $data = $data->find($id);
        } else if($user->type == 3){
            $data = $data->where('org_id',$user->org_id)->where('id',$id)->first();
        } else{
            $data = $data->where('team_id',$user->team_id)->where('id',$id)->first();
        }
        if(empty($data)){
            return $this->returnJSON(null, 10002, '此商品不存在');
        }
        return $this->returnJSON($data, 0, '');
    }

    public function display($id){
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Goods::whereIn('id',  $ids)->update(['is_display' => 0]);

        if ($result) {
            return $this->returnJSON(null, 0, '下架成功');
        }
    }

    public function isdisplay($id){
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Goods::whereIn('id',  $ids)->where('auto_time','>',date('Y-m-d h:i:s'))->update(['is_display' => 1]);

        if (!empty($result)) {
            return $this->returnJSON(null, 0, '上架成功');
        }else{
            return $this->returnJSON(null, 10003, '请修改商品自动下架时间 再进行此操作');
        }
    }

    public function update(Request $request,$id)
    {
        $user = $request->user();
        $this->validate($request, [
            'g_name' => 'required',
            'thumbnail' => 'required',
            'g_img' => 'required',
            'content' => 'required',
            'price' => 'required',
            'points' => 'required',
            'examine' => 'required',
            'org_id' => $user->type == 4 || $user->type == 5 ? 'required' : '',
            'team_id' => $user->type == 3 || $user->type == 4 ? 'required' : '',
        ]);

        if(!$this->isValidTime(request()->input('auto_time'), request()->input('end_time'))){
            return $this->returnJSON(null, 10005, '自动下架时间请小于线下兑换结束时间');
        }

        $data = Goods::find($id);

        $org_id = 0;
        $team_id = 0;
        if($user->type ==4 ){
            $org_id = $request->get('org_id', 0);
            $team_id = $request->input('team_id', 0);
        }
        if($user->type == 3) {
            $org_id = $user->org_id;
            $team_id = $request->input('team_id', 0);
        }
        if($user->type == 2) {
            $team = Team::where('id', $user->team_id)->first();
            if ($team->auth_create_goods == 0) {
                return $this->returnJSON(null, 10001, '权限不足');
            }
            $team_id = $user->team_id;
            $org_id = $user->org_id;
        }

        $all = $request->only([
            'g_name',
            'sponsor',
            'thumbnail',
            'g_img',
            'content',
            'access',
            'type',
            'price',
            'points',
            'g_num',
            'u_num',
            'auto_time',
            'examine',
            'is_display',
            'condition',
            'start_time',
            'end_time'
        ]);
        $all['team_id'] = $team_id;
        $all['org_id'] = $org_id;

        $data->fill($all);
        if($data->save())
        {
            return $this->returnJSON(null, 0, '保存成功');
        }

    }

    public function store(Request $request)
    {
        $user = $request->user();
        $this->validate($request, [
            'g_name' => 'required',
            'thumbnail' => 'required',
            'g_img' => 'required',
            'content' => 'required',
            'price' => 'required',
            'points' => 'required',
            'auto_time' => 'required',
            'examine' => 'required',
            'start_time' => 'required',
            'end_time' => 'required',
            'org_id' => $user->type == 4 || $user->type == 5 ? 'required' : '',
            'team_id' => $user->type == 3 || $user->type == 4 ? 'required' : '',
        ]);
        if(!$this->isValidTime(request()->input('auto_time'), request()->input('end_time'))){
            return $this->returnJSON(null, 10005, '自动下架时间请小于线下兑换结束时间');
        }
        $goods = new Goods();
        $org_id = 0;
        $team_id = 0;
        if($user->type ==4 ){
            $org_id = $request->get('org_id', 0);
            $team_id = $request->input('team_id', 0);
        }
        if($user->type == 3) {
            $org_id = $user->org_id;
            $team_id = $request->input('team_id', 0);
        }
        if($user->type == 2) {
            $team = Team::where('id', $user->team_id)->first();
            if ($team->auth_create_goods == 0) {
                return $this->returnJSON(null, 10001, '权限不足');
            }
            $team_id = $user->team_id;
            $org_id = $user->org_id;
        }

        if (!$org_id || !$team_id) {
            return $this->returnJSON(null, 10001, '请选择团队');
        }

        $goods->fill([
            'team_id' => $team_id,
            'org_id' => $org_id,
            'g_name' => $request->input('g_name'),
            'sponsor' => $request->input('sponsor'),
            'thumbnail' => $request->input('thumbnail'),
            'g_img' => $request->input('g_img'),
            'content' => $request->input('content'),
            'access' => $request->input('access'),
            'type' => $request->input('type', 0),
            'price' => $request->input('price'),
            'points' => $request->input('points'),
            'g_num' => $request->input('g_num'),
            'u_num' => $request->input('u_num'),
            'auto_time' => $request->input('auto_time'),
            'examine' => $request->input('examine'),
            'is_display' => $request->input('is_display', 0),
            'condition' => $request->input('condition'),
            'start_time' => $request->input('start_time'),
            'end_time' => $request->input('end_time'),

        ]);

        if($goods->save())
        {
            return $this->returnJSON(null, 0, '新增成功');
        }
    }

    public function top($id){
        $result = Goods::where('id',  $id)->update(['is_recommend' => 1]);

        if ($result) {
            return $this->returnJSON(null, 0, '置顶成功');
        }
    }

    public function down($id){

        $result = Goods::where('id',  $id)->update(['is_recommend' => 0]);

        if ($result) {
            return $this->returnJSON(null, 0, '取消成功');
        }
    }

    /**
     * 自动下架时间小于等于商品兑换截止时间
     * @param $t1 string auto_time
     * @param $t2 string end_time
     * @return bool
     */
    private function isValidTime($t1, $t2) {
        $beginDay = date('Y-m-d', strtotime($t1));
        $endDay = date('Y-m-d', strtotime($t2));
        if ($beginDay <= $endDay) {
            return true;
        }
        return false;
    }
}